package com.zidongxiangxi.sharding.job.core.listener;

import com.google.common.collect.ImmutableSet;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * 任务树节点变化监听
 *
 * @author chenxudong
 * @date 2021/02/20
 */
@Slf4j
public class JobTreeCacheListener implements TreeCacheListener {
    private final Set<TreeCacheEvent.Type> careEventTypes = ImmutableSet.of(
        TreeCacheEvent.Type.NODE_ADDED,
        TreeCacheEvent.Type.NODE_REMOVED,
        TreeCacheEvent.Type.NODE_UPDATED);

    private final List<NodeChangeListener> listeners;

    public JobTreeCacheListener(final List<NodeChangeListener> listeners) {
        this.listeners = Objects.isNull(listeners) ? new ArrayList<>() : listeners;
    }

    @Override
    public void childEvent(CuratorFramework client, TreeCacheEvent event) {
        if (!careEventTypes.contains(event.getType())) {
            return;
        }
        String path = event.getData().getPath();
        if (path.isEmpty()) {
            return;
        }
        String data = Objects.isNull(event.getData().getData()) ? "" : new String(event.getData().getData(), StandardCharsets.UTF_8);
        log.info("监听到节点变更：事件为：{}， 路径为：{}，数据为：{}", event.getType(), path, data);
        for (NodeChangeListener listener : listeners) {
            listener.dataChanged(path, event.getType(), data);
        }
    }
}
